package ru.smc.hogwarts.servlets.rooms;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Room;
import ru.smc.hogwarts.model.Student;

public class RoomsPopulate extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
       
    public RoomsPopulate() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
    	request.setAttribute("user", (String)session.getAttribute("userFN")+" "+session.getAttribute("userLN"));
    	
    	session.setAttribute("servletName", getServletName());
    	
    	long id = 0;
		long rid = 0;
    	
    	try {
			id = Long.parseLong(request.getParameter("id"));
			rid = Long.parseLong(request.getParameter("rid"));
		} catch (NumberFormatException e) {}
    	
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
    	
    	Student student = em.find(Student.class, id);
		Room room = em.find(Room.class, rid);
    	
    	if (student == null || room == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {    	
	    	Room room2 = student.getRoom();
	    	
			em.getTransaction().begin();
					
			if (room.getFull() != 4) {
				if (room2 != null) {room2.setFull(room2.getFull()-1);}
				room.setFull(room.getFull()+1);
				student.setRoom(room);
			} else if(room.getFull() == 4) {
				String error = "<span>К</span>омната максимально заселена.";
				session.setAttribute("error", error);
			}
			
			em.getTransaction().commit();
			
			response.sendRedirect(request.getContextPath() + "/rooms/info?id="+rid);
		}
		
    	em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
